import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import MainLayout from '@/layout/main/index.vue'
import Login from '@/views/account/login/login.vue'
import { useAuthStore } from '@/store/auth'
import { checkLogin } from '@/services/auth.service'
import { showLoad } from '@/store/load'
import { useMainStore } from '@/store'
import { appInitState } from '@/app'
import NProgress from 'nprogress'

let routeModules: any[] = []
const files = require.context('./modules', false, /.ts$/)
files.keys().forEach(f => {
  const out = files(f).default
  routeModules = [...routeModules, ...out]
})

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    meta: {
      title: '后台管理'
    },
    component: MainLayout,
    children: [
      ...routeModules
    ]
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '后台登陆'
    },
    component: Login
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  document.title = `${to.meta?.title}`
  NProgress.start()
  const authStore = useAuthStore()
  const mainStore = useMainStore()
  authStore.initSession()
  if (!authStore.isLogin && to.name !== 'Login') {
    next('/login')
    return
  }

  if (to.name !== 'Login') {
    checkLogin().then((info) => {
      authStore.setUser(info)
      if (!info.ok) {
        router.push('/login')
      } else if (!authStore.inited) {
        const load = showLoad()
        load.start()
        appInitState(router)
          .then((data) => {
            mainStore.updateSettings(data)
            authStore.setInit(true)
          })
          .finally(() => {
            load.finished()
          })
      }
    })
  }
  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
